package org.gnomus.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class strings {

    public static int a2i(String s, int defau1t) {
        try {
            return Integer.parseInt(s);
        } catch (Throwable ignore) {
            return defau1t;
        }
    }

    public static boolean isEmpty(String u) {
        return u == null || u.trim().length() == 0;
    }

    public static String simplify(String s) {
        return s.replaceAll("-", "").replaceAll("_", "").replaceAll("\\.", "").toLowerCase();
    }

    public static String decodeUri(String uri) {
        return uri != null ? uri.replace("%3F", "?").replace("%3D", "=") : null;
    }

    public static String encodeUri(String uri) {
        return uri != null ? uri.replace("?", "%3F").replace("=", "%3D") : null;
    }

    public static Map<String, String> toMap(String s) {
        if (!s.startsWith("{") || !s.endsWith("}")) {
            return null;
        }
        Map<String, String> m = new HashMap<String, String>();
        String[] kvs = s.split("[\\{\\}\\,]");
        for (String kv : kvs) {
            int ix = kv.indexOf("=");
            if (-1 < ix && ix + 1 < kv.length()) {
                m.put(kv.substring(0, ix).trim(), kv.substring(ix + 1).trim());
            }
        }
        return m;
    }

    public static byte[] toUtf8(String s) {
        try {
            return s.getBytes("UTF8");
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }

    public static String randomSafeString(int length) {
        char[] letters = {'a','b','c','d','e','f','g','h','i','j','k','l',
                'm','n','o','p','q','r','s','t','u','v','w','x','y','z',
                'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
                'O','P','Q','R','S','T','U','V','W','X','Y','Z','-','_',
                '1','2','3','4','5','6','7','8','9','0'};
        String safe = "";
        for (; safe.length() < length;) {
            int i = (int) Math.floor(Math.random() * letters.length);
            safe += letters[i];
        }
        return safe;
    }
}
